﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using VietTrips.Domain.Contexts;
using VietTrips.Domain.Interfaces;
using VietTrips.Domain.Models;

namespace VietTrips.Domain.Repositories
{
    public class TripRepository : ITripRepository
    {
        readonly TripContext _contexts = new TripContext();
        readonly SearchContext _contextSearch = new SearchContext();

        
        public void Dispose()
        {
            if (_contexts != null)
            {
                _contexts.Dispose();
            }
        }

        public IQueryable<Trip> All
        {
            get { return _contexts.Trips.Where(t => !t.IsDeleted); }
        }
        public IQueryable<Trip> AllIncluding(params Expression<Func<Trip, object>>[] includeExpressions)
        {
            throw new NotImplementedException();
        }

        public Trip Find(int id)
        {
            return _contexts.Trips.Find(id);
        }

        public void Insert(Trip entity)
        {
            _contexts.Trips.Add(entity);
            this.Save();
        }

        public void Update(Trip entity)
        {
            _contexts.Entry(entity).State = EntityState.Modified;
            this.Save();
        }

        public void Delete(int id)
        {
            // nếu tim dc trip
            var trip = _contexts.Trips.Find(id);
            if (trip != null)
            {
                // bật cờ
                trip.IsDeleted = true;
                // set time for modified
                trip.LastModified = DateTime.Now;
                _contexts.Entry(trip).State = EntityState.Modified;
            }
            this.Save();
            
        }

        public void Save()
        {
            _contexts.SaveChanges();
        }

        public List<ResultSearch> SearchByValues(Search search)
        {
            // call proc
            var result = _contextSearch.SearchProc.CallStoredProc(search);
            // get our results into a usable object
            return result.ToList<ResultSearch>();
        }

    }
}
